package com.zwy.Shopping.servlet_;

import com.zwy.Shopping.dao.UserDao;
import com.zwy.Shopping.dao.impl.UserDaoImpl;
import com.zwy.Shopping.model.CartItem;
import com.zwy.Shopping.model.User;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.List;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        UserDao userDao = new UserDaoImpl();
        String uname = request.getParameter("uname");
        System.out.println(uname);
        String pswd = request.getParameter("pswd");
        String usertype =  request.getParameter("optradio");
        if(usertype.equals("user")){
           User user = userDao.login(uname,pswd);
           if(user != null){
               //初始化cartItemList and cartItemNum
               int cartItemNum = 0;
               ServletContext application = this.getServletContext();
               List<CartItem> cartItemList =  (List<CartItem>) application.getAttribute("cartItemList");
               if(cartItemList!=null) {
                   for (CartItem cartItem : cartItemList) {
                       if (cartItem.getUserId() == user.getId()) {
                           cartItemNum++;
                       }
                   }
               }
               application.setAttribute("cartItemNum",cartItemNum);

            request.setAttribute("message","欢迎用户登录");
            request.setAttribute("page","index.jsp");
            request.getSession().setAttribute("user",user);//设置session域对象,方便后面调用
            request.getRequestDispatcher("alert.jsp").forward(request,response);
           }else{
            request.setAttribute("message","账号或密码错误");
            request.setAttribute("page","login.jsp");
            request.getRequestDispatcher("alert.jsp").forward(request,response);
           }
        }else {
            int id = Integer.parseInt(uname);
           boolean isLogin =  userDao.login(id,pswd);
           if(isLogin){
               request.setAttribute("message","欢迎管理员登录");
               request.setAttribute("page","admin_index.jsp");
               //设置session域对象,方便后面调用
               request.getRequestDispatcher("alert.jsp").forward(request,response);
           }
            request.setAttribute("message","账号或密码错误");
            request.setAttribute("page","login.jsp");
            request.getRequestDispatcher("alert.jsp").forward(request,response);

        }
    }
}
